#include "MainWindow.h"
#include "ButtonManager.h"

ButtonManager& ButtonManager::m_instance = ButtonManager();

ButtonManager::ButtonManager()
{
}

ButtonManager::~ButtonManager()
{
}

ButtonManager& ButtonManager::Instance()
{
	return (ButtonManager::m_instance);
}

void ButtonManager::addButton(AButton* _button)
{
	if (_button != NULL)
	{
		_button->initText();
		_button->setPosition(_button->Position.x, _button->Position.y);
		m_buttons.push_back(_button);
	}
}

void ButtonManager::clearButtons()
{
	std::vector<AButton*>::iterator it = m_buttons.begin();
	for (; it != m_buttons.end(); ++it)
		if (*it != NULL)
			delete *it;
	m_buttons.clear();
}

void ButtonManager::updateButtonEvent(AButton* _button)
{
	SDL_Event& e = MainWindow::Event();
	int x = 0, y = 0;

	SDL_GetMouseState(&x, &y);
	
	bool cond_x = (x >= _button->Position.x && x <= _button->Position.x + _button->CurrentSprite->Surface->w);
	bool cond_y = (y >= _button->Position.y && y <= _button->Position.y + _button->CurrentSprite->Surface->h);

	if (cond_x && cond_y)
	{
		if (e.type == SDL_MOUSEMOTION && _button->CurrentState == AButton::ButtonState::RELEASED)
		{
			_button->CurrentState = AButton::ButtonState::HOVERED;
			_button->updateState();
		}
		else if (e.type == SDL_MOUSEBUTTONDOWN)
		{
			_button->CurrentState = AButton::ButtonState::PRESSED;
			_button->updateState();
		}
		else if (e.type == SDL_MOUSEBUTTONUP)
		{
			if (_button->CurrentState == AButton::ButtonState::PRESSED)
			{
				_button->CurrentState = AButton::ButtonState::RELEASED;
				//_button->useCallBack();
				if (_button->CallBack(_button->Caller) == true)
					_button->updateState();
				e.type = SDL_MOUSEMOTION;
				SDL_PushEvent(&e);
			}
		}
	}
	else if (_button->CurrentState != AButton::ButtonState::RELEASED)
	{
		_button->CurrentState = AButton::ButtonState::RELEASED;
		_button->updateState();
	}
}

bool ButtonManager::update()
{
	std::vector<AButton*>::iterator it = m_buttons.begin();
	for (; it != m_buttons.end(); ++it)
	{
		if (*it != NULL)
		{
			this->updateButtonEvent(*it);
			if (MainWindow::ScreenHasChanged() == true)
			{
				MainWindow::ResetScreenChanged();
				return (false);
			}
		}
	}
	return (true);
}

bool ButtonManager::draw(SDL_Surface* _screen)
{
	std::vector<AButton*>::iterator it = m_buttons.begin();
	for (; it != m_buttons.end(); ++it)
	{
		if (*it != NULL)
		{
			(*it)->draw(_screen);
		}
	}
	return (true);
}

std::vector<AButton*> const& ButtonManager::getButtons() const
{
	return (m_buttons);
}